// pages/student/qingjiaxiangqing/qingjiaxiangqing.js
Page({
  data: {
    id: null,
    isLoading: true,
    leaveInfo: null
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.fetchLeaveDetail(options.id);
    } else {
      this.setData({
        isLoading: false
      });
    }
  },

  // 获取请假详情
  fetchLeaveDetail: function(id) {
    wx.showLoading({
      title: '加载中...',
    });

    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:3000/api/leaves/${id}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200 && res.data.success) {
          const leaveData = res.data.leave;
          
          // 格式化数据
          const formattedData = {
            id: leaveData.id,
            type: leaveData.type,
            status: this.formatStatus(leaveData.status),
            startTime: leaveData.startDate,
            endTime: leaveData.endDate,
            days: leaveData.days,
            reason: leaveData.reason,
            approver: leaveData.approverName || '待审批',
            approvalTime: leaveData.approveTime || '',
            comment: leaveData.approveRemark || '',
            attachment: leaveData.attachment || '',
            // 添加完整的附件URL
            attachmentUrl: leaveData.attachmentUrl || leaveData.attachment
          };
          
          this.setData({
            isLoading: false,
            leaveInfo: formattedData
          });
        } else {
          this.setData({
            isLoading: false
          });
          
          wx.showToast({
            title: res.data.message || '获取请假详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.hideLoading();
        
        this.setData({
          isLoading: false
        });
        
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 格式化请假状态
  formatStatus: function(status) {
    switch(status) {
      case 'pending': return '待审批';
      case 'approved': return '已批准';
      case 'rejected': return '已拒绝';
      default: return status;
    }
  },

  // 预览附件 - 修改为支持多种文件类型
  previewAttachment: function() {
    if (!this.data.leaveInfo || !this.data.leaveInfo.attachment) {
      wx.showToast({
        title: '没有附件',
        icon: 'none'
      });
      return;
    }
    
    // 构建完整的URL
    let attachmentUrl = this.data.leaveInfo.attachmentUrl || this.data.leaveInfo.attachment;
    
    // 如果是相对路径，转换为完整URL
    if (attachmentUrl.startsWith('/')) {
      attachmentUrl = 'http://localhost:3000' + attachmentUrl;
    }
    
    console.log('完整附件URL:', attachmentUrl); // 调试用
    
    // 显示加载中
    wx.showLoading({
      title: '加载中...',
    });
    
    // 获取文件扩展名
    const fileExt = attachmentUrl.substring(attachmentUrl.lastIndexOf('.') + 1).toLowerCase();
    
    // 图片类型直接预览
    if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExt)) {
      wx.previewImage({
        urls: [attachmentUrl],
        current: attachmentUrl,
        success: () => {
          wx.hideLoading();
        },
        fail: (err) => {
          wx.hideLoading();
          console.error('预览图片失败:', err);
          wx.showToast({
            title: '预览图片失败',
            icon: 'none'
          });
        }
      });
    } else {
      // 其他类型文件需要先下载再打开
      wx.downloadFile({
        url: attachmentUrl,
        success: (res) => {
          wx.hideLoading();
          if (res.statusCode === 200) {
            wx.openDocument({
              filePath: res.tempFilePath,
              success: () => {
                console.log('打开文档成功');
              },
              fail: (err) => {
                console.error('打开文档失败:', err);
                wx.showToast({
                  title: '无法打开此类型文件',
                  icon: 'none'
                });
              }
            });
          } else {
            wx.showToast({
              title: '文件下载失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.error('下载文件失败:', err);
          wx.showToast({
            title: '文件下载失败: ' + (err.errMsg || '未知错误'),
            icon: 'none'
          });
        }
      });
    }
  }
});